#!/usr/bin/python
'''
chooses most likely annotation for a list of overlapped gff.
'''
import sys

# parameters.
gff_file = sys.argv[1]
filter_file = sys.argv[2]
annot_file = sys.argv[3]


# read in filters.
to_check = []
fin = open(filter_file, "rb")
for line in fin:
	to_check.append(line.strip())
fin.close()

# read in gff.
gff = {}
fin = open(gff_file, "rb")
lines = fin.readlines()
fin.close()

i = 0
for line in lines:
	# tokenize.
	tmp = line.strip().split("\t")
	grp = tmp[8]
	
	tmp1 = grp.split(";")
	
	tmp2 = tmp1[0].split(":")[1]
	tmp3 = tmp2.split('"')
	rnd = tmp3[0]
	
	tmp4 = tmp3[1].strip().split(" ")
	start = int(tmp4[0])
	stop = int(tmp4[1])
	
	tmp5 = tmp1[1].split(":")[1]
	tmp6 = tmp5.split('"')
	ght = tmp6[0]
	
	# add to list.
	entry = (abs(start - stop), ght)
	if rnd not in gff:
		gff[rnd] = entry
		continue
		
	if entry[0] > gff[rnd]:
		gff[rnd] = entry
	
	
	#if i > 10000: break
	i += 1


# print out annotations.
to_check2 = {}
for ert in to_check:
#	print "%s\t%s" % (ert, gff[ert][1])
	to_check2[ert] = gff[ert][1]
	

# update annotations.
fin = open(annot_file, "rb")
lines = fin.readlines()
fin.close()

anots = []
for line in lines:
	tmp = line.strip().split()
	
	if tmp[0] in to_check2:
		tmp[1] = to_check2[tmp[0]]
		
	anots.append(tmp)
	
	
for anot in anots:
	print ' '.join(anot)
sys.exit()
